package com.zy.chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.chat.constants.constants;
import com.zy.chat.entity.GroupMessages;
import com.zy.chat.mapper.GroupMessageMapper;
import com.zy.chat.service.SaveGroupMessageService;
import com.zy.chat.vo.Groupmsgs;
import com.zy.chat.vo.GroupmsgsDoc;
import com.zy.chat.vo.RequestParams;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;


@Service
public class SaveGroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, GroupMessages> implements SaveGroupMessageService {


    @Autowired
    private GroupMessageMapper groupMessageMapper;



    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public Groupmsgs search(RequestParams params) {
        //准备Request
        SearchRequest request = new SearchRequest("groupmsg");
        //准备请求参数
        buildBasicQuery(params,request);
        //发送请求
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return handleResponse(response);
    }

    private Groupmsgs handleResponse(SearchResponse response) {
        //解析响应
        SearchHits searchHits = response.getHits();
        //总条数
        long total=searchHits.getTotalHits().value;
        //获取文档数组
        SearchHit[] hits = searchHits.getHits();
        //遍历
        ArrayList<GroupMessages> groupMessageslist = new ArrayList<>(hits.length);
        for(SearchHit hit:hits){
            //获取source
            String json=hit.getSourceAsString();
            //反序列化，非高亮的
            GroupMessages groupleMessages = JSON.parseObject(json, GroupMessages.class);
            //处理高亮结果
            //获取高亮map
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null && !map.isEmpty()) {
                // 2）根据字段名，获取高亮结果
                HighlightField highlightField = map.get("content");
                if (highlightField != null) {
                    // 3）获取高亮结果字符串数组中的第1个元素
                    String hName = highlightField.getFragments()[0].toString();
                    // 4）把高亮结果放到HotelDoc中
                    groupleMessages.setContent(hName);
                }
            }
            // 4.9.放入集合
            groupMessageslist.add(groupleMessages);
        }
        return new Groupmsgs(total,groupMessageslist);
    }

    public void buildBasicQuery(RequestParams params, SearchRequest request){
        //准备Boolean查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        String key=params.getKey();
        if(StringUtils.isNotBlank(key)){
            boolQuery.must(QueryBuilders.matchQuery("content",key));
        }
        //设置查询条件

        String touser=params.getTouser();
        boolQuery.filter(QueryBuilders.termQuery("groupName",touser));

        request.source().query(boolQuery);
    }
}
